<?php
namespace Crm\Domain;

use Crm\Common\Pager as Pager;
use Crm\Common\MetaData as MetaData;
use Crm\Model\WxUser as ModelWxUser;
use Crm\Model\WxUserFocus as UserFocus;

class WxUser
{
    /**
     * ado连接。
     *
     * @var object
     * @access pdo
     */
    public $pdo;

    public $metaData;
    public $check_option;
    public $unit_option; //商品单位

    public function __construct()
    {
        $this->pdo = \PhalApi\DI()->pdo;
        $this->metaData = new MetaData();

        $this->check_option = \PhalApi\DI()->config->get('basecode.check_option');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode'); //省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode'); //城市
        $this->unit_option = $this->metaData->getPairBaseCodeByType(20202); //商品单位
    }

    /* 根据appid获取小程序配置 */
    public function getAppInfo($appid){
        $sql = "select app_id,app_secret,app_token,app_name,app_mchid from wx_wechat where app_id='{$appid}'";
        $app = $this->pdo->getRow($sql);
        return $app;
    }

    /* 获取用户详情 */
    public function getUserInfo($user_id){
        $model = new ModelWxUser();
        return $model->getDetail($user_id);
    }

    /* 设置用户信息 */
    public function update($params,$user_id){
        $rlt = $this->pdo->update($params,'wx_user',$where='id='.$user_id);
        return $rlt;
    }

    /* 用户连续签到天数. */
    public function seriesSignNum($user_id){
        $sql = "select series_sign_num from wx_user where id={$user_id}";
        $num = $this->pdo->getRow($sql);
        return isset($num['series_sign_num'])?$num['series_sign_num']:0;
    }

    /* 用户关注 */
    public function attent($user_id,$data,$opt='sure'){
        if($opt=='sure') {
            $data['create_uid'] = $user_id;
            $data['create_date'] = time();
            switch ($data['type']){
                case 'info':
                    $msg = '关注';
                    break;
                case 'price':
                    $msg = '关注价格变动';
                    break;
                case 'open':
                    $msg = '关注开盘';
                    break;
                default:
                    $msg = '关注';
                    break;
            }
            if($data['type']=='info'){
                $this->pdo->doSql('update '.$data['action'].' set atme_num=atme_num+1 where id=' . $data['action_id']);
            }
            $sql = "select count(*) as cnt from wx_user_focus 
                      where action='".$data['action']."' and 
                      action_id=".$data['action_id']." and 
                      type='".$data['type']."'";
            $focus = $this->pdo->getRow($sql);
            if($focus['cnt']>0){
                $result = array('status' => '200', 'msg' => '您已'.$msg.'');
            }else{
                $rlt = $this->pdo->add($data, 'wx_user_focus');
                if($rlt){
                    $result = array('status' => '200', 'msg' => '恭喜您,关注成功');
                }else{
                    $result = array('status' => '200', 'msg' => '很抱歉,关注失败');
                }
            }
            return $result;
        }else{
            //用户取消关注
            if($data['type']=='info'){
                $this->pdo->doSql('update '.$data['action'].' set atme_num=atme_num-1 where id=' . $data['action_id']);
            }
            $model = new UserFocus();
            return $model->where('action_id',$data['action_id'])
                         ->where('action',$data['action'])
                         ->where('create_uid',$user_id)
                         ->where('type',$data['type'])
                         ->delete();
        }
    }

    /* 是否关注 */
    public function isAttent($user_id,$data){
        $sql = "select count(*) as cnt from wx_user_focus where action_id={$data['action_id']} and action='{$data['action']}' and type='{$data['type']}' and create_uid={$user_id}";
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']>0){
            return true;
        }else{
            return false;
        }
    }

    /*************** 房屋相关 *****************/
    /* 房屋列表. */
    public function houseList($data){
        $page_info = "";//url参数
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';//排序字段
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';//排序类型
        $pageSize = isset($data['pageSize']) ? $data['pageSize'] : 15;//分页，每页显示数量
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 1;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;

        $where = 'where 1=1 ';

        //是否有效
        $flag = isset($data['flag'])?$data['flag']:'1';
        if($flag!= ''){
            $where .= " and a.flag={$flag}";
            $page_info .="flag=".$flag."&";
            $filter['flag'] = $flag;
        }

        //商城ID
        $mall_id = isset($data['mall_id'])?$data['mall_id']:'';
        if($mall_id!= '') {
            $where .= " and a.mall_id={$mall_id}";
            $page_info .= "mall_id=" . $mall_id . "&";
            $filter['mall_id'] = $mall_id;
        }

        //项目信息(del)
        $project_id = isset($data['project_id'])?$data['project_id']:'';
        if($project_id!= '') {
            $where .= " and a.project_id={$project_id}";
            $page_info .= "project_id=" . $project_id . "&";
            $filter['project_id'] = $project_id;
        }

        //用户id
        $user_id = isset($data['user_id']) ? $data['user_id'] : 0;
        if($user_id!=0) {
            $where .= " and a.create_uid={$user_id}";
            $page_info .= "user_id=" . $user_id . "&";
            $filter['user_id'] = $user_id;
        }

        //兑换状态0未领取1已领取
        $status = isset($data['status'])?$data['status']:'';
        if($status!= ''){
            $where .= " and a.status={$status}";
            $page_info .="status=".$status."&";
            $filter['status'] = $status;
        }

        //关键字搜索
        $key = isset($data['key'])?$data['key']:'';
        if($key!= ''){
            $where .= " and (a.name like '%{$key}%' or a.mobile like '%{$key}%' ";
            $page_info .="key=".$key."&";
            $filter['key'] = $key;
        }

        $select_columns = "select %s from wx_user_house as a LEFT JOIN wx_user as b ON a.create_uid=b.id LEFT JOIN fc_project as c ON a.project_id=c.id %s %s %s";
        $select_count = "select %s from wx_user_house as a %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'a.*,b.name,b.nickname,b.mobile,b.headimgurl,c.name AS project_name',$where,$order,$limit);
        $sqlcount = sprintf($select_count,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'house');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['create_date_val'] = date('Y-m-d',$item['create_date']);
            $res[$key]['check_date_val'] = date('Y-m-d',$item['check_date']);
            $res[$key]['status_val'] = $this->check_option[$item['status']];
            //0:待审核 1:通过 9:不通过
            if($item['status']==0){
                $res[$key]['status_color'] = 'gray';
            }elseif ($item['status']==0){
                $res[$key]['status_color'] = 'green';
            }else{
                $res[$key]['status_color'] = 'orange';
            }

            //获取审核人信息
            if($item['check_uid']!=''){
                $sql = "select name,nickname from wx_user where id={$item['check_uid']}";
                $reward = $this->pdo->getRow($sql);
                $res[$key]['check_name'] = empty($reward['name'])?$reward['nickname']:$reward['name'];
            }
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 房屋添加 */
    public function addHouse($user_id,$data){
        //判断用户是否提交过房屋验证
        $sql = "select id from wx_user_house where flag=1 and project_id='{$data['project_id']}' and build_no='{$data['build_no']}' 
                    and unit_no='{$data['unit_no']}' and house_no='{$data['house_no']}'";
        $rlt = $this->pdo->getAll($sql);
        if(count($rlt)==0) {
            $userInfo = $this->getUserInfo($user_id);
            if($userInfo['name']!='' && $userInfo['mobile']!='') {
                $data['create_date'] = time();//申请时间
                $data['create_uid'] = $user_id;//创建人
                $data['owner_uid'] = $user_id;//申请人
                $data['name'] = $userInfo['name'];//申请姓名
                $data['mobile'] = $userInfo['mobile'];//申请人电话
                $insertId = $this->pdo->add($data, 'wx_user_house');
                //返回添加房屋信息
                $sql = "select a.id,a.create_date,a.create_uid,a.project_id,a.build_no,a.unit_no,a.house_no,a.status,b.name as project_name from wx_user_house as a LEFT JOIN fc_project as b on a.project_id=b.id where a.id={$insertId}";
                $info = $this->pdo->getRow($sql);
                $result = array('status'=>200,'info'=>$info,'msg' => '恭喜您,申请成功');
            }else{
                $result = array('status'=>201,'msg' => '请您先完善个人信息后,再申请业主认证!');
            }
        }else{
            if($rlt['owner_uid']==$user_id){
                $result = array('status'=>201,'msg' => '您已经申请该房屋认证!');
            }else{
                $result = array('status'=>201,'msg' => '该房屋已被他人申请!');
            }

        }
        return $result;
    }

    /* 用户房屋详情 */
    public function houseInfo($user_id,$data){
        $where = ' a.flag=1 and a.create_uid='.$user_id;
        if(isset($data['project_id']) && !empty($data['project_id'])){
            $where .= " AND a.project_id = ".$data['project_id'];
        }
        if(isset($data['build_no']) && !empty($data['build_no'])){
            $where .= " AND a.build_no = '".$data['build_no']."'";
        }
        if(isset($data['unit_no']) && !empty($data['unit_no'])){
            $where .= " AND a.unit_no = '".$data['unit_no']."'";
        }
        if(isset($data['house_no']) && !empty($data['house_no'])){
            $where .= " AND a.house_no = '".$data['house_no']."'";
        }
        $sql = "select a.id,a.create_date,a.create_uid,a.project_id,a.build_no,a.unit_no,a.house_no,a.status,b.name as project_name from wx_user_house as a LEFT JOIN fc_project as b on a.project_id=b.id where ".$where;
        $info = $this->pdo->getRow($sql);
        $info['status_val'] = $this->check_option[$info['status']];
        return $info;
    }

    /* 用户房屋推荐人设置(推荐人设置) */
    public function setHouseRecommend($user_id,$data){
        //查询推荐人是否在系统中
        $sql = "select id,name,mobile from wx_user where mall_id={$data['mall_id']} and mobile='{$data['mobile']}'";
        $user = $this->pdo->getRow($sql);
        if(isset($user['id']) && $user['id']>0) {
            $set['check_recommend_date'] = time();//推荐人时间
            $set['check_recommend_uid'] = $user_id;//推荐人人
            $set['recommend_uid'] = $user['id'];
            $rlt = $this->pdo->update($set, 'wx_user_house', ' id=' . $data['user_house_id']);
            if ($rlt) {
                $result = array('status' => 200, 'id' => $rlt, 'msg' => '恭喜您,设置成功!');
            } else {
                $result = array('status' => 201, 'msg' => '很抱歉,设置失败!');
            }
        }else{
            $result = array('status' => 202, 'msg' => '很抱歉,该用户还没有注册系统!');
        }
        return $result;
    }

    /* 用户房屋验证(业主认证) */
    public function verifyHouse($user_id,$data){
        $data['check_date'] = time();//审核时间
        $data['check_uid'] = $user_id;//审核人
        $data['des'] = $data['des'];//审核意见
        $data['status'] = $data['status'];//审核状态
        $rlt = $this->pdo->update($data,'wx_user_house',' id='.$data['user_house_id']);
        if($rlt) {
            $this->pdo->update(array('user_type'=>8),'wx_user',' id='.$data['owner_uid']);
            $result = array('status' => 200, 'id' => $rlt, 'msg' => '恭喜您,审核成功!');
        }else{
            $result = array('status' => 200, 'id' => $rlt, 'msg' => '很抱歉,审核失败!');
        }
        return $result;
    }

    /** 用户老带新推荐认证
     * todo:1、一个用户可能推荐同一用户购买同一项目的多套房源(如经纪人)
     */
    public function verifyRecommend($user_id,$data){
        $mobile = isset($data['mobile'])?$data['mobile']:'';
        $project_id = isset($data['project_id'])?$data['project_id']:'';
        $mall_id = isset($data['mall_id'])?$data['mall_id']:'';
        if($mall_id!='' && $project_id!='' && $mobile!='') {
            $where = " a.flag=1 and a.project_id={$project_id} and mall_id={$mall_id} and a.recommend_uid={$user_id} and a.mobile='{$mobile}'";
            $sql = "select a.* from wx_user_house as a  where " . $where;
            $info = $this->pdo->getRow($sql);
            if(isset($info['id'])) {
                //用户获得积分
                $scoreDomain = new Score();
                $isObtain = $scoreDomain->checkObtainScore($user_id,'2020303','wx_user_house',$info['id'],$mall_id);
                if($isObtain){
                    $rlt = $scoreDomain->addScore($user_id, '2020303', 'wx_user_house', $info['id'], $mall_id);
                    $result = array('status' => 200,'score'=>$rlt, 'data' => $info, 'msg' => '认证成功,获得积分!');
                }else{
                    $result = array('status'=>200,'msg' => '认证成功!');
                }
            }else{
                $result = array('status'=>200,'msg' => '抱歉,认证信息不存在!');
            }
        }else{
            $result = array('status'=>200,'msg' => '非法信息!');
        }
        return $result;
    }

    /*************** 奖品相关 *****************/
    /* 奖品兑换列表. */
    public function awardList($data){
        $page_info = "";//url参数
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';//排序字段
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';//排序类型
        $pageSize = isset($data['pageSize']) ? $data['pageSize'] : 15;//分页，每页显示数量
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 1;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;

        $where = 'where 1=1 ';

        //是否有效
        $flag = isset($data['flag'])?$data['flag']:'1';
        if($flag!= ''){
            $where .= " and a.flag={$flag}";
            $page_info .="flag=".$flag."&";
            $filter['flag'] = $flag;
        }

        //商城ID
        $mall_id = isset($data['mall_id'])?$data['mall_id']:'';
        if($mall_id!= '') {
            $where .= " and a.mall_id={$mall_id}";
            $page_info .= "mall_id=" . $mall_id . "&";
            $filter['mall_id'] = $mall_id;
        }

        //项目信息(del)
        $project_id = isset($data['project_id'])?$data['project_id']:'';
        if($project_id!= '') {
            $where .= " and a.project_id={$project_id}";
            $page_info .= "project_id=" . $project_id . "&";
            $filter['project_id'] = $project_id;
        }

        //用户id
        $user_id = isset($data['user_id']) ? $data['user_id'] : 0;
        if($user_id!=0) {
            $where .= " and a.create_uid={$user_id}";
            $page_info .= "user_id=" . $user_id . "&";
            $filter['user_id'] = $user_id;
        }

        //兑换状态0未领取1已领取
        $status = isset($data['status'])?$data['status']:'';
        if($status!= ''){
            $where .= " and a.status={$status}";
            $page_info .="status=".$status."&";
            $filter['status'] = $status;
        }

        $select_columns = "select %s from wx_user_award as a LEFT JOIN mk_mall_award as b ON a.award_id = b.id LEFT JOIN wx_user as c ON a.create_uid=c.id %s %s %s";
        $select_count = "select %s from wx_user_award as a %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'a.*,b.name AS award_name,b.price AS award_price,b.score AS award_score,b.img_url,b.unit,c.name,c.nickname,c.mobile',$where,$order,$limit);
        $sqlcount = sprintf($select_count,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'awardConvert');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['create_date_val'] = date('Y-m-d',$item['create_date']);
            $res[$key]['reward_date_val'] = date('Y-m-d',$item['reward_date']);
            $res[$key]['status_val'] = $item['status']==0?'未领取':'已领取';
            $res[$key]['status_color'] = $item['status']==0?'blue':'green';
            $res[$key]['img_url_s'] = str_replace('.','_s.',$item['img_url']);
            $res[$key]['unit_val'] = $this->unit_option[$item['unit']];
            //获取对奖人信息
            if($item['reward_uid']!=''){
                $sql = "select name,nickname from wx_user where id={$item['reward_uid']}";
                $reward = $this->pdo->getRow($sql);
                $res[$key]['reward_name'] = empty($reward['name'])?$reward['nickname']:$reward['name'];
            }
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 用户兑奖(奖品发放) */
    public function awardGive($user_id,$data){
        //判断用户是否已经领取奖品
        $sql = "select count(*) as cnt from wx_user_award where flag=1 and id={$data['user_award_id']} and status=1";
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']==0) {
            $data['reward_date'] = time();//兑奖时间(领取时间)
            $data['reward_uid'] = $user_id;//兑奖人(发奖人)
            $data['status'] = 1;//设置兑奖状态
            $rlt = $this->pdo->update($data,'wx_user_award',' id='.$data['user_award_id']);
            if($rlt) {
                $result = array('status' => 200, 'id' => $rlt, 'msg' => '恭喜您,发放成功!');
            }else{
                $result = array('status' => 200, 'id' => $rlt, 'msg' => '很抱歉,发放失败!');
            }
        }else{
            $result = array('status'=>200,'msg' => '该用户已经领取该奖品!');
        }
        return $result;
    }

}
